package logic

import (
	"context"
	"encoding/json"
	"time"
	"ture/models/cache"
	"ture/models/mysql"

	"ture/turerpc/internal/svc"
	"ture/turerpc/turerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type TrueListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTrueListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TrueListLogic {
	return &TrueListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *TrueListLogic) TrueList(in *turerpc.TrueListRequest) (*turerpc.TrueListResponse, error) {
	// todo: add your logic here and delete this line

	var ture []mysql.True
	result, _ := cache.Rdb.Get(l.ctx, "tureList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&ture)
		marshal, _ := json.Marshal(ture)
		cache.Rdb.Set(l.ctx, "tureList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &ture)
	}
	var tureList []*turerpc.TrueList

	for _, m := range ture {
		list := turerpc.TrueList{
			Id:    int64(m.ID),
			Title: m.Title,
			Name:  m.Name,
			Price: float32(m.Price),

			ClassId: m.ClassId,
			BrandId: m.BrandId,
		}
		tureList = append(tureList, &list)
	}
	return &turerpc.TrueListResponse{
		List: tureList,
	}, nil
}
